<template>
  <transition name="fade">
    <div
      v-show="visible"
      class="back-to-top"
      @click="scrollToTop"
    >
      <div class="back-to-top-content">
        <i class="el-icon-top"></i>
        <span>回顶部</span>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: 'BackToTop',
  data() {
    return {
      visible: false,
      scrollTop: 0
    }
  },
  mounted() {
    this.handleScroll()
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll() {
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
      this.visible = this.scrollTop > 300
    },
    scrollToTop() {
      // 平滑滚动到顶部
      const scrollStep = -window.scrollY / (500 / 15)
      const scrollInterval = setInterval(() => {
        if (window.scrollY !== 0) {
          window.scrollBy(0, scrollStep)
        } else {
          clearInterval(scrollInterval)
        }
      }, 15)
    }
  }
}
</script>

<style scoped>
.back-to-top {
  position: fixed;
  right: 20px;
  bottom: 80px;
  z-index: 1000;
  cursor: pointer;
  user-select: none;
}

.back-to-top-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.back-to-top-content:hover {
  background-color: #f5f7fa;
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  transform: translateY(-2px);
}

.back-to-top-content i {
  font-size: 18px;
  color: #606266;
  margin-bottom: 2px;
}

.back-to-top-content span {
  font-size: 12px;
  color: #606266;
  line-height: 1;
}

.back-to-top-content:hover i,
.back-to-top-content:hover span {
  color: #409eff;
}

/* 淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .back-to-top {
    right: 15px;
    bottom: 60px;
  }
  
  .back-to-top-content {
    width: 45px;
    height: 45px;
  }
  
  .back-to-top-content i {
    font-size: 16px;
  }
  
  .back-to-top-content span {
    font-size: 11px;
  }
}
</style>
